package com.liveneo.system.base.utils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.liveneo.adapter.base.support.LogUtils;

/**
 * 
 * @author wangchaochao
 *
 */
public class JsonUtils {
    private static Logger       logger       = LoggerFactory.getLogger(JsonUtils.class);
    /**
     * 
     */
    private static ObjectMapper objectMapper = new ObjectMapper();
    // 日期格式化
    static {
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.setSerializationInclusion(Include.NON_EMPTY);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 将java对象转换成json字符串
     * 
     * @param obj
     *            准备转换的对象
     * @return json字符串
     * @throws Exception
     */
    public static String beanToJson(Object obj) {
        try {
            String json = objectMapper.writeValueAsString(obj);
            return json;
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return null;
        }
    }

    /**
     * 将json字符串转换成java list对象
     * 
     * @param json
     *            准备转换的json字符串
     * @param cls
     *            准备转换的类
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> jsonToList(String json, Class<T> elementClasses) {
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, elementClasses);
            return (List<T>) objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return null;
        }
    }

    /**
     * 将json字符串转换成java map对象
     * 
     * @param json
     *            准备转换的json字符串
     * @param cls
     *            准备转换的类
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static <K, V> Map<K, V> jsonToMap(String json, Class<K> keyClasses, Class<V> valueClasses) {
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(HashMap.class, keyClasses, valueClasses);
            return (Map<K, V>) objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return null;
        }
    }

    /**
     * 将java对象转换成json字符串
     * 
     * @param obj
     *            准备转换的对象
     * @return json字符串
     * @throws Exception
     */
    public static String beanToJson(Object obj, boolean notNull) {
        try {
            String json = objectMapper.writeValueAsString(obj);
            return json;
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return null;
        }
    }

    /**
     * 将java对象转换成json字符串
     * 
     * @param obj
     *            准备转换的对象
     * @return json字符串
     * @throws Exception
     */
    public static String toJson(Object obj) {
        return beanToJson(obj, true);
    }

    public static String toJsonFormatDate(Object obj) {
        return beanToJson(obj);
    }

    /**
     * 将json字符串转换成java对象
     * 
     * @param json
     *            准备转换的json字符串
     * @param cls
     *            准备转换的类
     * @return
     * @throws Exception
     */
    public static Object jsonToBean(String json, String className) {
        try {
            Object bean = objectMapper.readValue(json, Class.forName(className));
            return bean;
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return null;
        }
    }

    public static Object fromJsonWithBase64(String logTitle, String base64JsonData, Class<?> type, String enc) {
        // 对象转换成Json字符串
        String jsonStrWithBase64 = null;
        try {
            // base64解密
            jsonStrWithBase64 = new String(Base64.decodeBase64(base64JsonData.getBytes(enc)), enc);
            LogUtils.info(logTitle + "接收报文信息【" + jsonStrWithBase64 + "】");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        Object obj = jsonToBean(jsonStrWithBase64, type.getName());
        return obj;
    }

    /**
     * base64加密字符串转换为对象（使用UTF-8编码）
     * 
     * @return 对象的json的base64加密串
     * @throws UnsupportedEncodingException
     */
    public static <T> T fromJsonWithBase64(String logTitle, String base64JsonData, Class<T> type) {
        return (T) fromJsonWithBase64(logTitle, base64JsonData, type, "UTF-8");
    }

    /**
     * 将json字节数组转换成java对象
     * 
     * @param json
     *            准备转换的json字符串
     * @param cls
     *            准备转换的类
     * @return
     * @throws Exception
     */
    public static Object jsonToBean(byte[] jsonByte, Class<?> cls) {
        try {
            Object bean = objectMapper.readValue(jsonByte, cls);
            return bean;
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return null;
        }
    }

    /**
     * 将json字节数组转换成java对象
     * 
     * @param json
     *            准备转换的json字符串
     * @param cls
     *            准备转换的类
     * @return
     * @throws Exception
     */
    public static <T> T jsonToRealBean(byte[] jsonByte, Class<T> cls) {
        try {
            T bean = objectMapper.readValue(jsonByte, cls);
            return bean;
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return null;
        }
    }

    /**
     * 将json字节数组转换成java对象
     * 
     * @param json
     *            准备转换的json字符串
     * @param cls
     *            准备转换的类
     * @return
     * @throws Exception
     */
    public static <T> T jsonToRealBean(String json, Class<T> cls) {
        try {
            T bean = objectMapper.readValue(json, cls);
            return bean;
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            return null;
        }
    }
}